/*
 * COMP6471 Project
 *  
 * This file is created by Yuan Tao (ewan.msn@gmail.com)
 * Licensed under GNU GPL v3
 * 
 * $Author: ewan.msn@gmail.com $
 * $Date: 2011-10-12 03:14:14 +0000 (Wed, 12 Oct 2011) $
 * $Rev: 29 $
 * $HeadURL: http://comp6471.googlecode.com/svn/Project4/src/kklib/InputLoader.java $
 * 
 */

package kklib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import util.logger;

public class InputLoader {
	public static final int MAX_FILES = 50;
	
	// load one text file and store the data of file in the Layout objects.
	public int loadTextFile(String fileFullname, Layout layout) {
        String line;
        BufferedReader in;
        
		try {
			in = new BufferedReader(new FileReader(fileFullname));
	        line = in.readLine();        
	        while(line != null) {
	        	layout.txtFileData.add(line.toUpperCase());
	            line = in.readLine();
	        }
		} catch (FileNotFoundException e) {
			logger.err("File not found: " + fileFullname);
			return -1;
		} catch (IOException e) {
			e.printStackTrace();
			logger.err(e.getMessage());
			return -1;
		}
		
		layout.fileFullname = fileFullname;		// it indicates the file loaded successfully
		
		return 0;
	}
	
	// load all files under a directory
	public int loadTextFiles(String dirPath, ArrayList<Layout> layouts) {
        File filesDir = new File(dirPath);
        
        File list[] = filesDir.listFiles();
        if (list.length > MAX_FILES) {
			logger.output("Too many files under directory: " + dirPath);
			return -1;
		}
        
        for(int i=0;i<list.length;i++)
        {
            if(list[i].isFile())
            {
            	String fileFullname =dirPath + "\\" + list[i].getName(); 
            	logger.info(fileFullname);
            	
            	// load the file
            	Layout layout = new Layout();  // create the layout
            	
            	// set default table size
            	layout.gameSize = 4;
            	for (int j = 0; j < Cage.MAX_TYPES; j++) {
					Cage c = new Cage();
					c.cageNum = 0;
					c.cageType = j + 1;
					layout.availableCages.add(c);
				}
            	
            	if (loadTextFile(fileFullname, layout) != 0) {
					logger.output("Fail to load txt file: " + fileFullname);
					continue;
				}
                
                layouts.add(layout);
            }
        }
		return 0;
	}
	
	// parse the input file of project2.
	public int fileDataParserForCages(Layout layout) {
		ArrayList<String> strList = layout.txtFileData;
		
		for (int i = 0; i < strList.size(); i++) {
			String line = strList.get(i).trim();
			StringTokenizer st = new StringTokenizer(line, "="); 
			int cnt = st.countTokens();
			if (cnt < 1) {		// skip the empty line
				continue;
			}

			// try to get the table size
			// eg: GameSize = 3
			String str = st.nextToken().trim();
			if (str.equalsIgnoreCase("GameSize")) {
				String strGameSize = st.nextToken().trim();
				try {
					layout.gameSize = Integer.parseInt(strGameSize);
				} catch (NumberFormatException e) {
					logger.parserErr(layout.fileFullname, "Cannot get game size from string: " + line);
					return -1;
				}
			}
			
			// get the number of cages
			// eg: NumberOfEachShape = A:7 B:1
			if (str.equalsIgnoreCase("NumberOfEachShape")) {
				String strTypes = st.nextToken().trim().toUpperCase();
				StringTokenizer stCages = new StringTokenizer(strTypes); 
				
				int numOfTypes = stCages.countTokens();
				while (numOfTypes-- > 0) {
					int type = 0;
					int num = 0;
					String strType = stCages.nextToken();
					
					if (strType.length() < 3) {
						logger.parserErr(layout.fileFullname, "Cannot get cage type from string: " + strType);
						return -1;
					}
					
					type = strType.charAt(0) - 'A' + 1;
					if (type < 1 || type > Cage.MAX_TYPES) {
						logger.parserErr(layout.fileFullname, "Cannot get cage type from string: " + strType);
						return -1;
					}
					
					// check the duplicated one
					if (layout.availableCages.get(type - 1).cageNum != 0) {
						logger.parserErr(layout.fileFullname, "Get duplicated type from string: " + strTypes);
						return -1;
					}
					
					try {
						num = Integer.parseInt(strType.substring(2));
					} catch (NumberFormatException e) {
						logger.parserErr(layout.fileFullname, "Cannot get cage number from string: " + strType);
						return -1;
					}
					
					// add the cage to the list
					layout.availableCages.get(type - 1).cageNum = num;					
				}
			}
			
		}
		return 0;
	}
}
